import * as d3 from "d3"
import moment from "moment"
import eventHub from "./utils/eventHub"
import { createClipPath } from "./gantt.axis"
const _clipId = "rectGroupClipId"

const RECTCLASS = 'rect-cell'

export function drawPlans(svg, ctx) {
    // if (ctx.rectGroup) {
    //     ctx.rectGroup.remove()
    //     ctx.rectGroup = null
    // }

    if (!ctx.rectGroup) {
        ctx.rectGroup = svg.append("g").attr("class", "rectGroup").attr("clip-path", `url(#${_clipId})`)
    }


    const { marginLeft, marginTop, marginRight, marginBottom, width, height } = ctx

    const clipRect = {
        x: marginLeft,
        y: marginTop,
        width: width - marginLeft - marginRight,
        height: height - marginTop - marginBottom
    }

    createClipPath(svg, _clipId, clipRect)

    let plans = ctx.plans || []

    plans.forEach((r, index) => {
        let planGroupId = `planGroup-${index}`
        let planGroup = ctx.rectGroup.select(`#${planGroupId}`)
        if (planGroup.empty()) {
            planGroup = ctx.rectGroup.append("g").attr("id", planGroupId)
        }
        drawPlanRow(planGroup, ctx, r)
    })

    // drawDeadTime(svg, ctx)
}

function drawPlanRow(planGroup, ctx, planRow) {
    let { key: yK, plans, label: yName } = planRow
    let { _yScale: yScale, _xScale: xScale } = ctx

    if (!yScale || !xScale) return
    let step = yScale.bandwidth()
    let h = step * 0.8
    let yValue = yScale(yK) + step * 0.5
    let y1 = yValue - h * 0.5
    let y2 = yValue + h * 0.5

    let valid = isFinite(yValue) && isFinite(h)
    if (!valid) return

    // console.log("*drawPlanRow", step, yScale(yK), yName)

    let group = planGroup

    // group.attr("tranform", `translate(0,${yScale(yK)})`)


    let fill = "rgba(0,255,0,0.4)"
    let stroke = "rgba(255,255,0,0.8)"
    const rx = 8, ry = 8

    const duration = 100

    const ease_ = d3.easeLinear

    const enterFn = enter => {
        enter.append("rect")
            .attr("class", RECTCLASS)
            .attr("x", d => {
                let s = moment(d.start).startOf("day")
                let x1 = xScale(s)
                return x1
            })
            .attr("y", y1)
            .attr("width", 0)
            .attr("height", h)
            .attr("fill", fill)
            .attr("stroke-width", 1)
            .attr("stroke", stroke)
            .attr("rx", rx)
            .attr("ry", ry)
            .on("mouseenter", (event, d) => {
                const { clientX, clientY } = event
                let { start, end } = d
                let tipKey = `${yName}-${start}-${end}`
                // console.log("mouseenter", tipKey, clientX, clientY)
                eventHub.emit("mouseenter", tipKey, clientX, clientY)

            })
            .on("mousemove", (event, d) => {
                const { clientX, clientY } = event
                let { start, end } = d
                let tipKey = `${yName}-${start}-${end}`
                // console.log("mousemove", tipKey, clientX, clientY)
                eventHub.emit("mousemove", tipKey, clientX, clientY)
            })
            .on("mouseleave", (event, d) => {
                const { clientX, clientY } = event
                let { start, end } = d
                let tipKey = `${yName}-${start}-${end}`
                // console.log("mouseleave", tipKey)
                eventHub.emit("mouseleave", tipKey, clientX, clientY)

            })
            .transition()
            .ease(ease_)
            .duration(duration)
            .attr("width", d => {
                const { start, end } = d
                let s = moment(start).startOf("day")
                let e = moment(end).startOf("day")
                let x1 = xScale(s)
                let x2 = xScale(e)
                let width = x2 - x1
                return width
            }).on("end", (d) => {
                // console.log("enter add end", d.id)
            })
    }


    const updateFn = update => {
        update.each(function (d) {
            let rect = d3.select(this)
            rect
                .attr("x", d => {
                    let s = moment(d.start).startOf("day")
                    let x1 = xScale(s)
                    return x1
                })
                .attr("y", y1)
                .attr("width", d => {
                    const { start, end } = d
                    let s = moment(start).startOf("day")
                    let e = moment(end).startOf("day")
                    let x1 = xScale(s)
                    let x2 = xScale(e)
                    let width = x2 - x1
                    return width
                })

        })

    }


    const exitFn = exit => {
        // debugger
        exit.each(function (d) {

            let rect = d3.select(this)
            let ieEmpty = rect.empty()
            if (!ieEmpty) {
                rect.transition().ease(ease_).duration(duration).attr("width", 0).on("end", (d) => {
                    // console.log("exit remove end", d.id)
                }).remove()

            }

        })
    }


    group
        .selectAll(`.${RECTCLASS}`)
        .data(plans, d => {
            return d.id
        })
        .join(enterFn, updateFn, exitFn)

}


function appendRect(group, rectConfig) {
    const { fill, x, y, width, height, stroke, tipKey, rx = 8, ry = 8, className = "rect-cell" } = rectConfig || {}

    let rect = group.append("rect")
        .attr("class", className)
        .attr("fill", fill)
        .attr("x", x)
        .attr("y", y)
        .attr("rx", rx)
        .attr("ry", ry)
        .attr("width", width)
        .attr("height", height)
        .attr("stroke-width", 1)
        .attr("stroke", stroke)
        .on("mouseenter", (event) => {
            const { clientX, clientY } = event
            // console.log("mouseenter", tipKey, clientX, clientY)
            eventHub.emit("mouseenter", tipKey, clientX, clientY)

        })
        .on("mousemove", event => {
            const { clientX, clientY } = event
            // console.log("mousemove", tipKey, clientX, clientY)
            eventHub.emit("mousemove", tipKey, clientX, clientY)
        })
        .on("mouseleave", () => {
            const { clientX, clientY } = event
            // console.log("mouseleave", tipKey)
            eventHub.emit("mouseleave", tipKey, clientX, clientY)

        })

    return rect
}

function drawDeadTime(svg, ctx) {
    if (ctx.deadLineGroup) {
        ctx.deadLineGroup.remove()
        ctx.deadLineGroup = null
    }
    if (!ctx.deadLineGroup) {
        ctx.deadLineGroup = svg.append("g").attr("class", "rectGroup").attr("clip-path", `url(#${_clipId})`)
    }

    let group = ctx.deadLineGroup

    let deadTime = ctx.deadTime
    if (!deadTime) return

    let yScale = ctx._yScale
    let xScale = ctx._xScale
    if (!yScale || !xScale) return

    let tipKey = `截止时间-${moment(deadTime).format("YYYY-MM-DD")}`

    let t1 = moment(deadTime).startOf("day")
    let t2 = moment(deadTime).endOf("day")

    let x1 = xScale(t1)
    let x2 = xScale(t2)
    let width = x2 - x1
    let y = 0
    let h = ctx.height

    let fill = "rgba(0,0,255,0.6)"
    let stroke = "rgba(255,255,0,0.8)"
    let rectConfig = { fill, x: x1, y, width, height: h, stroke, tipKey, className: "deadtime-cell" }
    appendRect(group, rectConfig)


}